package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.ruoyi.common.annotation.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.*;

@Service
public class C2CICDRunningTimeService {
    @Autowired
    private DruidDataSource druidDataSource;

    /**
     * 获取所有 versionNo 对应的节点名称和运行时间，并按 buildTime 排序
     * 返回格式：{ "versionNo": [ { "nodeName": "Node1", "runTime": "120" }, ... ] }
     */
    public Map<String, List<Map<String, Object>>> getRunningTimeByVersion() {
        // 查询增加 buildTime 并按其排序
        String query = "SELECT versionNo, nodeName, runTime, buildTime FROM cicd_integrated_info ORDER BY buildTime ASC";
        Map<String, List<Map<String, Object>>> result = new HashMap<>();

        try (Connection connection = druidDataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement(query);
             ResultSet resultSet = statement.executeQuery()) {

            while (resultSet.next()) {
                String versionNo = resultSet.getString("versionNo");
                String nodeName = resultSet.getString("nodeName");
                String runTime = resultSet.getString("runTime");
                String buildTime = resultSet.getString("buildTime");

                // 跳过 null 或空的 versionNo
                if (versionNo == null || versionNo.isEmpty()) {
                    continue;
                }

                // 构建节点信息
                Map<String, Object> nodeData = new HashMap<>();
                nodeData.put("nodeName", nodeName);
                nodeData.put("runTime", runTime);
                nodeData.put("buildTime", buildTime); // 可选：保留 buildTime 供前端调试或显示

                // 如果版本号已存在于结果中，追加数据；否则创建新列表
                result.computeIfAbsent(versionNo, k -> new ArrayList<>()).add(nodeData);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error fetching data from database", e);
        }

        return result;
    }


    public Map<String, List<Map<String, Object>>> getRunningTimeByNaturalWeek() {
        String query = "SELECT buildTime, versionNo, nodeName, runTime FROM cicd_integrated_info";
        Map<String, List<Map<String, Object>>> result = new HashMap<>();

        // 日期时间格式，用于解析 buildTime
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        WeekFields weekFields = WeekFields.of(Locale.getDefault());

        try (Connection connection = druidDataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement(query);
             ResultSet resultSet = statement.executeQuery()) {

            while (resultSet.next()) {
                String buildTimeStr = resultSet.getString("buildTime");
                String versionNo = resultSet.getString("versionNo");
                String nodeName = resultSet.getString("nodeName");
                String runTime = resultSet.getString("runTime");

                // 跳过无效数据
                if (buildTimeStr == null || buildTimeStr.isEmpty() || versionNo == null || versionNo.isEmpty()) {
                    continue;
                }

                // 解析 buildTime 为 LocalDateTime
                LocalDateTime buildTime = LocalDateTime.parse(buildTimeStr, dateTimeFormatter);

                // 计算自然周
                int year = buildTime.getYear();
                int week = buildTime.get(weekFields.weekOfWeekBasedYear());

                // 计算该自然周的开始和结束日期
                LocalDate startOfWeek = LocalDate.from(buildTime.with(weekFields.weekOfWeekBasedYear(), week).with(DayOfWeek.MONDAY));
                LocalDate endOfWeek = startOfWeek.plusDays(6); // 星期天是该周的结束日

                // 使用日期格式化器格式化日期为 yyyy/MM/dd
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                String dateRange = startOfWeek.format(dateFormatter) + "-" + endOfWeek.format(dateFormatter);

                // 构建自然周的标识
                String naturalWeek = dateRange;

                // 构建节点信息
                Map<String, Object> nodeData = new HashMap<>();
                nodeData.put("versionNo", versionNo);
                nodeData.put("nodeName", nodeName);
                nodeData.put("runTime", runTime);
                nodeData.put("timePeriod", naturalWeek); // 添加具体时间段


                // 按自然周分组
                result.computeIfAbsent(naturalWeek, k -> new ArrayList<>()).add(nodeData);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error fetching data from database", e);
        }

        // 对 result 按自然周的起始日期排序
        LinkedHashMap<String, List<Map<String, Object>>> sortedResult = new LinkedHashMap<>();
        result.entrySet().stream()
                .sorted(Comparator.comparing(entry -> extractStartDate(entry.getKey())))
                .forEachOrdered(entry -> sortedResult.put(entry.getKey(), entry.getValue()));

        return sortedResult;
    }

    private LocalDate extractStartDate(String naturalWeek) {
        try {
            // 提取自然周的起始日期（"yyyy/MM/dd"）
            String startDateStr = naturalWeek.split("-")[0]; // 提取起始日期部分
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            return LocalDate.parse(startDateStr, formatter);
        } catch (Exception e) {
            // 如果格式不匹配，抛出异常并记录错误
            throw new IllegalArgumentException("Invalid naturalWeek format: " + naturalWeek, e);
        }
    }

}
